// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include "connectionhandler.h"
#include "devicefinder.h"
#include "devicehandler.h"
#include "heartrate-global.h"

#include <QQmlApplicationEngine>
#include <QQmlContext>

#include <QGuiApplication>

#include <QCommandLineParser>
#include <QCommandLineOption>
#include <QLoggingCategory>

#include <QtDebug>
#include <QStandardPaths>

#include <QFile>
#include <QDir>
#include <QFileDialog>

#include <QThread>

#ifdef Q_OS_WIN
bool simulator = false;         //没搞明白simulator作用。哦，哦，后面又重新赋值simulator了。
#else
bool simulator = true;
#endif

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    //QByteArray bin_dat;
    char bin_dat[1024*200];     //200KiB

    //QQ不理解QComandLineParser用处？
    QCommandLineParser parser;
    parser.setApplicationDescription("Bluetooth Low Energy Heart Rate Game");
    parser.addHelpOption();
    parser.addVersionOption();
    QCommandLineOption simulatorOption("simulator", "Simulator");
    parser.addOption(simulatorOption);

    QCommandLineOption verboseOption("verbose", "Verbose mode");
    parser.addOption(verboseOption);
    parser.process(app);

    if (parser.isSet(verboseOption))
        QLoggingCategory::setFilterRules(QStringLiteral("qt.bluetooth* = true"));
    simulator = parser.isSet(simulatorOption);



    ConnectionHandler connectionHandler;
    DeviceHandler deviceHandler;                    //看到了对象（类的实例），构造简单。
    DeviceFinder deviceFinder(&deviceHandler);      //看到了对象（类的实例），它构造时，用了DeviceHandler对象。
    //QStandardPaths standardPaths;

    QQmlApplicationEngine engine;
    engine.setInitialProperties({
        {"connectionHandler", QVariant::fromValue(&connectionHandler)},
        {"deviceFinder", QVariant::fromValue(&deviceFinder)},
        {"deviceHandler", QVariant::fromValue(&deviceHandler)}
    });

    /*在CMakeList.txt中，已添加qrc:/qml资源，可以使用此资源下的文件：qrc:/qml/xxx.qml。
     * qt6_add_resources(heartrate-game "qml"
        PREFIX
            "/"
        FILES
            ${qml_resource_files}
        )
     *
    */
    //engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));       //QQ是否可以省略qrc，即用":/qml/main.qml"。QQ资源名qml如何使用？
    //engine.load(QUrl(QStringLiteral(":/qml/main.qml")));          //已试，不行。shit,以":"开头没意义。
    engine.load(QStringLiteral("qrc:/qml/main.qml"));               //前面不加qrc，可以显示，但是放大了的，加上qrc后就好了。
    //engine.load(QStringLiteral(":/qml/main.qml"));                  //不行。放大了的页面。
    if (engine.rootObjects().isEmpty())
        return -1;

    qDebug()<<"系统字体目录"<<QStandardPaths::standardLocations(QStandardPaths::FontsLocation);
    qDebug()<<"系统桌面目录"<<QStandardPaths::standardLocations(QStandardPaths::DesktopLocation);
    qDebug()<<"系统文档目录"<<QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);
    qDebug()<<"系统临时文件目录"<<QStandardPaths::standardLocations(QStandardPaths::TempLocation);
    qDebug()<<"系统缓存目录"<<QStandardPaths::standardLocations(QStandardPaths::CacheLocation);
    qDebug()<<"APP目录"<<QStandardPaths::standardLocations(QStandardPaths::ApplicationsLocation);
     qDebug()<<"GenericData目录"<<QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation);
    qDebug()<<"AppData目录"<<QStandardPaths::standardLocations(QStandardPaths::AppDataLocation);
    qDebug()<<"APPLocalData目录"<<QStandardPaths::standardLocations(QStandardPaths::AppLocalDataLocation);
    qDebug()<<"APPConfig目录"<<QStandardPaths::standardLocations(QStandardPaths::AppConfigLocation);
    qDebug()<<"APP应用目录"<<app.applicationDirPath();  //输出："/data/app/org.qtproject.example.heartrate_game--r2LBOLnv0trmrlm60KKnA==/lib/arm64"
    qDebug()<<"APP文件目录"<<app.applicationFilePath(); //输出："/data/app/org.qtproject.example.heartrate_game-qFQ7Oc8T4iBKXBtKOLiaQA==/lib/arm64/libheartrate-game_arm64-v8a.so"
    qDebug()<<"APP PID"<<app.applicationPid();
    qDebug()<<"Build time:xzzz";


    //for test.
    //QDirIterator it()
    QStringList file_list;
    QDir binDir("/sdcard/DT45G");   //".bin", QDir::Name, QDir::Files. !!已验证，目录"/sdcard/DT45GXX"不存在，目录"/sdcard/DT45G"存在。

    if(binDir.exists()){
        qDebug("/sdcard/DT45G ok");
    }
    else{
        qDebug("err:/sdcard/DT45G");
    }

    file_list= binDir.entryList({"*.bin"}, QDir::Files, QDir::NoSort);//QDir::AllEntries, QDir::NoSort);  //QDir::Files
    qDebug()<< "files num="<<file_list.size();
//    qDebug()<< "file_1"<< file_list.value(0);
//    qDebug()<< "file_2" << file_list.value(1);
//    qDebug()<< "file_3" << file_list.value(2);
//    qDebug()<< "file_4" << file_list.value(3);
    qDebug()<< "files" << file_list;

    deviceFinder.bin_list= binDir.entryList({"*.bin"}, QDir::Files, QDir::NoSort);
    qDebug()<< "files(*):"  <<deviceFinder.bin_list;

    qDebug()<<"xxx" <<binDir.path();
    qDebug()<< "abs path:"<< binDir.absolutePath();
    qDebug()<<"dir name"<< binDir.dirName();

    QString path;
    path= binDir.filePath("3.txt");
    qDebug()<< "path ..."<< path;



//    for (int var = 0; var < file_list.size(); ++var) {
//        q
//    }


    //end for test.


    //试试这些SD卡的目录名称。/mnt/sdcard/  可以，/storage/sdcard0/ 不可，/storage/sdcard/ 不可。/mnt/user/0/ 不可。QQ但是/storage/sdcard0/ ->/sdcard，这个应该可以。
    QString file_name="/sdcard/DT45G/DT45G_08008000.bin";
//    QString file_name = QFileDialog::getOpenFileName(this, tr("选择文件"), "./",
//                                     tr("文件(*.*)"));

    QFile file(file_name);
//    if(true == file.setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner))
//        qDebug()<<"setPermissions ok";
//    else
//        qDebug()<<"err:setPermissions";

    QString err;
    if(true == file.exists()){

        qDebug()<<"name="<< file.fileName();
        qDebug()<<"size="<< file.size();

        if(true == file.open(QIODeviceBase::ReadOnly, QFileDevice::ReadGroup)){
            //qDebug()<<"open ok";
            LOGD("open ok:%s", file_name.toStdString().c_str());

            //读取1024
            qint32 cnt= 0;
            qint64 cnt_read;
            while(1){
                cnt_read = file.read(bin_dat, 1024);

                //cnt++;

                qDebug()<< "read count:"<< cnt_read<<"/"<<cnt;

                //QThread::msleep(10);

                if(1024 != cnt_read)
                  break;
            }

            //qDebug()<<"pos:"<< file.pos();
            printf("pos:%lld", file.pos());     //打印到控制台？
            //qDebug()<< "Last read:"<<file.read(bin_dat, 1024);
        }
        else{
            err=file.errorString();
            //qDebug()<<"open err:"<< err;
            LOGD("open err:%s", err.toStdString().c_str());
        }
    }
    else
        qDebug()<<file.fileName()<< "NOT exist";

    QFile file2("/sdcard/111/wr3.txt");

     //QFile file2("/mnt/sdcard/111/wr2.txt");
    if(1){//(true != file2.exists()){
        if(true == file2.open(QIODevice::ReadWrite)){
            qDebug()<< "create file2";
            qint64 cnt;
            cnt= file2.write("12345678");

            qDebug()<<"file2 write ok"<< cnt;
            file2.flush();
            file2.close();

        }
        else{
            qDebug()<<"err: create file2"<<file2.errorString();
        }
    }
    //Environment.getExternalStorageDirectory().getAbsolutePath();
    qDebug()<<"shit"<< connectionHandler.save_dir.toString();

    return app.exec();
}
